package com.stylefeng.guns.modular.huamao.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.modular.huamao.aliyun.OSSResultModel;
import com.stylefeng.guns.modular.huamao.common.FileUtils;
import com.stylefeng.guns.modular.huamao.dao.MessagesMapper;
import com.stylefeng.guns.modular.huamao.model.Messages;
import com.stylefeng.guns.modular.huamao.model.MessagesList;
import com.stylefeng.guns.modular.huamao.service.IMessagesService;
import com.stylefeng.guns.modular.huamao.service.ISktShopsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * <p>
 * 系统消息表 服务实现类
 * </p>
 *
 * @author gxz123
 * @since 2018-04-24
 */
@Service
public class MessagesServiceImpl extends ServiceImpl<MessagesMapper, Messages> implements IMessagesService {

    @Autowired
    private MessagesMapper mm;
    @Autowired
    private ISktShopsService sktShopsService;
    @Autowired
    private FileUtils fileUtils;

    // 通过传过来的ID进行逻辑删除
    @Override
    public void deleteById2(Integer id) {
        mm.deleteById2(id);
    }

    // 系统消息展示
    @Override
    public List<MessagesList> selectMessagesAll(Page<MessagesList> page, MessagesList messagesList) {
        Integer total =mm.selectMessagesAllCount(messagesList);
        page.setTotal(total);
        return mm.selectMessagesAll(page,messagesList);
    }

    // 获取用户
    @Override
    public List<MessagesList> getUsers(String userPhone) {
        return mm.getUsers(userPhone);
    }

    /**
     * 添加信息，传过来一个实体需要判断，如果messagesList.getUsersId()为空说明是给所有商家发送，需要先查出来所有的是商家的userId，
     * 不为空，说明是给指定用户发送，直接写添加sql
     *
     * 消息类型：0手工 1系统
     */
    @Override
    @Transactional
    public boolean addMessages(Integer msgType, Integer sendUserId, List<Integer> usersId, String msgContent, String msgJson) {
        try {
            Messages messages = null;
            //new一个list保存对象，用于批量添加
            List<Messages> list = new ArrayList<Messages>();
            Boolean b = false;
            Integer add = 0;
            if (usersId == null || usersId.size() == 0) {
                //给所有商家发消息,先查询所有的商家的userId
                List<Integer> userIds = sktShopsService.selectAllId();
                messages = new Messages();
                // 消息类型 0手动 1系统
                messages.setMsgType(msgType);
                // 写入实体类发送者id
                messages.setSendUserId(sendUserId);
                //消息内容
                messages.setMsgContent(msgContent);
                //存放json数据
                messages.setMsgJson(msgJson);
                // 发送时间为当前是时间
                messages.setCreateTime(new Date());
                Integer integer = mm.shopAddMessages(messages, userIds);
                if(integer != 0){
                     b = true;
                }
            } else {
                //遍历添加到list中
                for (Integer userId :
                        usersId) {
                    messages = new Messages();
                    // 消息类型 0手动 1系统
                    messages.setMsgType(msgType);
                    // 写入实体类发送者id
                    messages.setSendUserId(sendUserId);
                    //接收者id
                    messages.setReceiveUserId(userId);
                    //消息内容
                    messages.setMsgContent(msgContent);
                    //存放json数据
                    messages.setMsgJson(msgJson);
                    // 发送时间为当前是时间
                    messages.setCreateTime(new Date());
                    list.add(messages);
                }
                //批量添加
                EntityWrapper<Messages> entityWrapper = new EntityWrapper<Messages>(messages);
                b = this.insertBatch(list);
            }
            return b;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }



    /**
     * 图片上传阿里云
     * @return
     * @throws IOException
     */
    @Override
    public Map<String,Object> upload(HttpServletRequest req){
        Map<String,Object> result = new HashMap<String, Object>();

        MultipartHttpServletRequest mReq  =  null;
        MultipartFile file = null;
        InputStream is = null ;
        OSSResultModel ossResult = null;
        String fileName = "";
        // 原始文件名   UEDITOR创建页面元素时的alt和title属性
        String originalFileName = "";

        try {
            mReq = (MultipartHttpServletRequest)req;
            // 从config.json中取得上传文件的ID
            file = mReq.getFile("file");
            // 取得文件的原
            fileName = file.getOriginalFilename();
            originalFileName = fileName;
            if(!StringUtils.isEmpty(fileName)){
                is = file.getInputStream();
                fileName = fileUtils.reName(fileName);
                ossResult = fileUtils.saveFile(fileName, is);
            } else {
                throw new IOException("文件名为空!");
            }

            String[] strings = new String[5];
            strings[0] = ossResult.getUrl();


            result.put("errno",0);
            result.put("data",strings);
        }
        catch (Exception e) {
            result.put("errno",1);
            result.put("data","");
            System.out.println("文件 "+fileName+" 上传失败!");
        }

        return result;
    }

}
